package com.su.lightthings.fragment.device

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.su.lightthings.R
import com.su.lightthings.adapter.DeviceListAdapter
import com.su.lightthings.base.BaseFragment
import com.su.lightthings.bean.DeviceListBean
import com.su.lightthings.databinding.FragmentDeviceListBinding
import com.su.lightthings.view.LinearSpacingItemDecoration
import com.su.lightthings.viewmodel.CommonViewModel

class DeviceListFragment : BaseFragment<FragmentDeviceListBinding>() {

    companion object {
        private const val TAG = "DeviceListFragment"
    }

    private val mAdapter: DeviceListAdapter by lazy {
        DeviceListAdapter()
    }

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentDeviceListBinding =
        FragmentDeviceListBinding.inflate(layoutInflater)

    override fun initViews() {
        binding.rv.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
            addItemDecoration(LinearSpacingItemDecoration(bottom = 10))
        }
        val testList = mutableListOf<DeviceListBean>().apply {
            add(DeviceListBean(R.drawable.device_style_watch_c, "测试一", "已连接", "30"))
            add(DeviceListBean(R.drawable.device_style_watch_1_c, "测试二", "未连接", "20"))
        }
        mAdapter.submitList(testList)
        mAdapter.setOnItemClickListener { _, _, i ->
            if (i < testList.size) {
                Log.d(TAG, testList[i].deviceName)
                toDevice()
            } else {
                addDevice()
            }
        }
        binding.ivBack.setOnClickListener {
            requireActivity().finish()
        }
        binding.ivAdd.setOnClickListener {
            addDevice()
        }
    }

    override fun onResume() {
        super.onResume()
        reqPermission()
    }

    private fun addDevice() {
        findNavController().navigate(R.id.action_deviceListFragment_to_addDeviceFragment)
    }

    private fun toDevice() {
        findNavController().navigate(R.id.action_deviceListFragment_to_watchDetailFragment)
    }

    private fun reqPermission() {
        CommonViewModel.INSTANCE.doPermissionTask(0, requireContext())
    }

}